package cn.pigeon.health.service;

import cn.pigeon.health.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private Map<String, User> map = new HashMap<>();

    private void initData(){
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));

        User user2 = new User();
        user2.setUsername("limin");
        user2.setPassword(passwordEncoder.encode("limin"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
        User findUser = map.get(username);
        if(findUser==null){
            //无此用户
            return null;
        }
        String password = findUser.getPassword();

        List<GrantedAuthority> list = new ArrayList<>();
        if(findUser.getUsername().equalsIgnoreCase("admin")){
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("list"));
            list.add(new SimpleGrantedAuthority("delete"));
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }else{
            list.add(new SimpleGrantedAuthority("list"));
        }


        UserDetails user = new org.springframework.security.core.userdetails.User(findUser.getUsername(),password,list);
        return user;
    }
}
